from PySide6.QtWidgets import QLineEdit, QLabel, QWidget
from PySide6.QtCore import QRegularExpression
from PySide6.QtGui import QRegularExpressionValidator


class Input(QWidget):
    DEFAULT_HEIGHT = 30

    def __init__(self, parent, title, maxLength=16, inputType='string'):
        super(Input, self).__init__(parent)
        self.setFixedHeight(Input.DEFAULT_HEIGHT)

        self.labTitle = QLabel(title + ':', self)
        self.labTitle.setGeometry(0, 0, len(title) * self.labTitle.font().pointSize() + 5, Input.DEFAULT_HEIGHT)

        self.edit = QLineEdit(self)
        self.tailWidget = self.edit
        self.setMaxLength(maxLength)
        self.setInputType(inputType)

        self.setFixedSize(self.edit.pos().x() + self.edit.width(), Input.DEFAULT_HEIGHT)

    def numberEditChange(self):
        if len(self.text) == 0:
            self.text = 0

    def textChange(self, changeEvent):
        self.edit.textChanged.connect(changeEvent)

    def setMaxLength(self, maxLength):
        self.edit.setMaxLength(maxLength)
        self.edit.setFixedWidth(maxLength * 10)
        self.edit.setGeometry(self.labTitle.width(), 0, self.edit.width(), self.edit.height())
        self.refresh()

    def setInputType(self, inputType):
        if inputType == 'number':
            validator = QRegularExpressionValidator(self)
            validator.setRegularExpression(QRegularExpression('[0-9]+$'))
            self.edit.setValidator(validator)
            self.edit.textChanged.connect(self.numberEditChange)

    @property
    def text(self):
        return self.edit.text()

    @text.setter
    def text(self, text):
        self.edit.setText(str(text))

    def setPos(self, x, y):
        self.setGeometry(x, y, self.width(), self.height())

    def refresh(self):
        if self.tailWidget != self.edit:
            self.tailWidget.setGeometry(
                self.edit.x() + self.edit.width(), 0,
                self.tailWidget.width(), self.tailWidget.height()
            )

        self.setFixedWidth(self.tailWidget.x() + self.tailWidget.width())

    def addTail(self, widget: QWidget):
        widget.setParent(self)
        self.tailWidget = widget
        self.refresh()
